<?php

namespace App\Http\Controllers;

use App\Models\Expert;
use App\Models\Video;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class VideoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $oVideo=Video::orderBy('id','asc')->paginate(4);
        return view("admin.video-list")->with("oVideo",$oVideo);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $oExpert=Expert::all();
        return view("admin.add-video")->with('oExpert',$oExpert);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 定义验证规则和错误消息
        $rules = [
            'name' => 'required',
            'website' => 'required',
            'profile' => 'required',
            'start_at' => 'required',
            'end_at' => 'required',
        ];

        $messages = [
            'name.required' => '标题不能为空',
            'website.required' => '视频路径不能为空',
            'profile.required' => '课程简介不能为空',
            'start_at.required' => '直播开始时间不能为空',
            'end_at.required' => '直播结束时间不能为空',
        ];

        // 验证输入数据
        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            // 如果验证失败,返回错误消息
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // 创建新的视频实例
        $video = new Video();

        // 填充视频信息
        $video->name = $request->input('name');
        $file=$request->file('website');
        $ext=$file->extension();
        $filename=time().".".$ext;
        $file->move(public_path()."/upload",$filename);
        $video["website"]='/upload/'.$filename;

       // $video->website = $request->input('website');
        $video->type = $request->input('type');
        $video->profile = $request->input('profile');
        $video->start_at = $request->input('start_at');
        $video->end_at = $request->input('end_at');

        // 处理缩略图上传
        if ($request->hasFile('upload_file')) {
            $image = $request->file('upload_file');
            $imageName = time() . '_' . $image->getClientOriginalName();
            $image->move(public_path('upload/video_thumb'), $imageName);
            $video->thumb = '/upload/video_thumb/' . $imageName;
        }

        // 保存视频信息
        $video->save();

        // 处理关联专家
        $expertIds = $request->input('expertid');
        $video->experts()->sync($expertIds); // 使用sync方法更新视频与专家的关联关系

        return redirect()->route('video.index')->with('success', '视频添加成功');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $oVideo=Video::find($id);
        $oExpert=Expert::all();
        return view('admin.edit-video')
            ->with('oVideo',$oVideo)
            ->with('oExpert',$oExpert);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $video = Video::find($id);

        if (!$video) {
            // 处理视频不存在的情况，可以返回错误信息或重定向
        }

        // 更新视频信息
        $video->name = $request->input('name');
        $video->website = $request->input('website');
        $video->type = $request->input('type');
        $video->profile = $request->input('profile');
        $video->start_at = $request->input('start_at');
        $video->end_at = $request->input('end_at');

        // 处理缩略图上传
        if ($request->hasFile('upload_file')) {
            $image = $request->file('upload_file');
            $imageName = time() . '_' . $image->getClientOriginalName();
            $image->move(public_path('upload/video_thumb'), $imageName);
            $video->thumb = '/upload/video_thumb/' . $imageName;
        }

        // 保存视频信息
        $video->save();

        // 处理关联专家
        $expertIds = $request->input('doc_id'); // 前端传递的专家id数组为doc_id

        $video->experts()->sync($expertIds); // 使用sync方法更新视频与专家的关联关系

        return redirect()->route('video.index')->with('success', '视频已更新');
    }

    public function uploadDocThumb(Request $request)
    {
        if ($request->hasFile('upload_file')) {
            $file = $request->file('upload_file');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $destinationPath = public_path('/thumbnails');
            $file->move($destinationPath, $fileName);

            // 返回JSON响应
            return response()->json([
                'success' => true,
                'photo' => '/thumbnails/' . $fileName
            ]);
        }

        return response()->json([
            'success' => false,
            'msg' => '文件上传失败'
        ]);
    }
    public function destroy($id)
    {
        //
        $video=Video::find($id);
        $expert=$video->experts;
        $video->experts()->detach($expert);
        $video->delete();
        return json_encode(['msg'=>'删除成功']);
    }
}
